<template>
  <div class="property-repair-report">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item label="小区">
        <el-select v-model="filters.communityId" placeholder="请选择小区" size="small" style="width: 200px;" @change="handleCommunityChange">
          <el-option label="全部小区" value="" />
          <el-option 
            v-for="community in communityList" 
            :key="community.id" 
            :label="community.name" 
            :value="community.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="搜索">
        <el-input 
          v-model="filters.searchText" 
          placeholder="请输入报修单号、业主ID或问题描述" 
          size="small" 
          style="width: 300px;"
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
        <el-button size="small" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 调试信息 -->
    <div style="margin: 10px 0; color: #666;">
      当前数据条数: {{ tableData.length }}, 总记录数: {{ total }}
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;" :default-sort="{prop: 'priority', order: 'ascending'}">
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="orderNo" label="报修单号" width="120" />
      <el-table-column prop="ownerId" label="业主ID" width="100" />
      <el-table-column prop="repairTypeId" label="维修类型" width="100">
        <template slot-scope="scope">
          <span>{{ repair_type.find(item => item.id === scope.row.repairTypeId)?.name || '未知' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="问题描述" />
      <el-table-column prop="appointmentTime" label="预约时间" width="120" />
      <el-table-column prop="priority" label="紧急程度" width="100" sortable="custom" :sort-method="sortByPriority">
        <template slot-scope="scope">
          <el-tag :type="priorityTagType(scope.row.priority)">{{ urgencyLevelText(scope.row.priority) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTagType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150" />
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="handleAudit(scope.row)">审核</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right;"
    />
    
    <!-- 审核对话框 -->
    <el-dialog title="维修审核" :visible.sync="auditDialogVisible" width="600px">
      <el-form :model="auditForm" :rules="auditRules" ref="auditForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报修单号">
              <el-input v-model="auditForm.orderNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业主ID">
              <el-input v-model="auditForm.ownerId" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房屋ID">
              <el-input v-model="auditForm.houseId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修类型">
              <el-input v-model="auditForm.repairTypeName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="问题描述">
          <el-input type="textarea" v-model="auditForm.description" :rows="3" disabled />
        </el-form-item>
        
        <!-- 图片展示区域始终显示 -->
        <el-form-item label="报修图片">
          <template v-if="auditImageUrl && !imageLoadError">
            <img :src="auditImageUrl" alt="报修图片" style="max-width: 100%; max-height: 200px; border: 1px solid #eee; border-radius: 4px;" @error="imageLoadError = true" />
          </template>
          <template v-else-if="imageLoadError">
            <div style="width: 100%; height: 120px; display: flex; align-items: center; justify-content: center; background: #f5f5f5; color: #d9534f; border: 1px dashed #eee; border-radius: 4px;">图片加载错误</div>
          </template>
          <template v-else>
            <div style="width: 100%; height: 120px; display: flex; align-items: center; justify-content: center; background: #f5f5f5; color: #999; border: 1px dashed #eee; border-radius: 4px;">暂无图片</div>
          </template>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约时间">
              <el-input v-model="auditForm.appointmentTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急程度">
              <el-tag :type="priorityTagType(auditForm.priority)">{{ urgencyLevelText(auditForm.priority) }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="2">已受理</el-radio>
            <el-radio :label="7">已驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="处理人ID" prop="handlerId" v-if="auditForm.status === 2">
          <el-select v-model="auditForm.handlerId" placeholder="请选择处理人员" style="width: 100%;">
            <el-option
              v-for="staff in propertyStaffList"
              :key="staff.id"
              :label="`${staff.accountName}（${staff.phone || ''}）`"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="驳回原因" v-if="auditForm.status === 7" prop="cancelReason">
          <el-input type="textarea" v-model="auditForm.cancelReason" :rows="3" placeholder="请输入驳回原因" />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">确认审核</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PropertyRepairReport',
  data() {
    return {
      repair_type: [
        {
        id: 1,
        name:'水电维修'
      },
      {
        id: 2,
        name:'门窗维修'
      },
      {
        id: 3,
        name:'管道疏通'
      },
    ],
      filters: {
        searchText: '',
        communityId: ''
      },
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      auditDialogVisible: false,
      auditForm: {
        orderNo: '',
        ownerId: '',
        houseId: '',
        repairTypeName: '',
        description: '',
        appointmentTime: '',
        priority: 1,
        status: 1,
        handlerId: '',
        cancelReason: '',
        id: ''
      },
      auditImageUrl: '',
      imageLoadError: false,
      auditRules: {
        status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
        handlerId: [{ required: true, message: '请输入处理人ID', trigger: 'blur' }],
        cancelReason: [
          { 
            required: true, 
            message: '请输入驳回原因', 
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.auditForm.status === 7 && !value) {
                callback(new Error('请输入驳回原因'));
              } else {
                callback();
              }
            }
          }
        ]
      },
      // 小区列表
      communityList: [],
      // 物业人员列表
      propertyStaffList: []
    }
  },
  mounted() {
    // 组件加载时获取第一页数据
    this.loadData();
    // 获取小区列表
    this.loadCommunityList();
    // 获取物业人员列表
    this.loadPropertyStaffList();
  },
  computed: {
    // 移除filteredTableData，现在使用后端分页
  },
  methods: {
    handleSearch() {
      // 如果搜索条件为空，加载所有数据
      if (!this.filters.searchText.trim()) {
        this.loadData();
        return;
      }
      
      // 调用后端接口进行搜索
      this.$axios.post('/api/queryAll/repair', {
        describe: this.filters.searchText,
        communityId: this.filters.communityId,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        console.log('后端返回数据:', res.data);
        // 检查返回的数据结构
        if (res.data && res.data.content) {
          this.tableData = res.data.content;
          this.total = res.data.totalElements;
          console.log('设置tableData:', this.tableData);
          this.$message.success(`搜索完成，找到 ${this.total} 条记录`);
        } else if (res.data.code === 200 && res.data.data) {
          // 如果数据包装在data字段中
          this.tableData = res.data.data.content;
          this.total = res.data.data.totalElements;
          console.log('设置tableData:', this.tableData);
          this.$message.success(`搜索完成，找到 ${this.total} 条记录`);
        } else {
          this.$message.error('数据格式错误');
        }
      }).catch(error => {
        this.$message.error('网络错误，请稍后重试');
        console.error('搜索错误:', error);
      });
    },
    handleReset() {
      this.filters.searchText = '';
      this.filters.communityId = '';
      this.currentPage = 1;
      this.pageSize = 10;
      this.loadData();
      this.$message.success('搜索条件已重置');
    },
    handleView(row) {
      this.$message.info(`查看报修单：${row.orderNo}`);
    },
    handleAudit(row) {
      this.auditForm = {
        orderNo: row.orderNo,
        ownerId: row.ownerId,
        houseId: row.houseId,
        repairTypeName: this.repair_type.find(item => item.id === row.repairTypeId)?.name || '未知',
        description: row.description,
        appointmentTime: row.appointmentTime,
        priority: row.priority,
        status: row.status,
        handlerId: '',
        cancelReason: '',
        id: row.id
      };
      this.auditDialogVisible = true;
      this.auditImageUrl = '';
      this.imageLoadError = false;
      // 如果已有处理人，预先选中
      if (row.handlerId) {
        this.auditForm.handlerId = row.handlerId;
      }
      // 新增：获取图片链接
      this.$axios.get("/repair/getImageById/"+row.id).then(res => {
        if (res.data && res.data.data && res.data.data.url) {
          this.auditImageUrl = res.data.data.url;
        } else if (res.data && res.data.url) {
          this.auditImageUrl = res.data.url;
        } else if (typeof res.data === 'string') {
          this.auditImageUrl = res.data;
        } else {
          this.auditImageUrl = '';
        }
        this.imageLoadError = false;
      }).catch(() => {
        this.auditImageUrl = '';
        this.imageLoadError = false;
      });
    },
    handleDelete(row) {
      this.$confirm('确定要删除该报修单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('删除成功（模拟）');
      });
    },
    statusText(status) {
      switch (status) {
        case 1: return '待审核';
        case 2: return '已受理';
        case 3: return '维修中';
        case 4: return '待验收';
        case 5: return '已完成';
        case 6: return '已取消';
        case 7: return '已驳回';
        default: return '未知';
      }
    },
    statusTagType(status) {
      switch (status) {
        case 1: return 'info';
        case 2: return 'warning';
        case 3: return 'primary';
        case 4: return 'warning';
        case 5: return 'success';
        case 6: return 'danger';
        case 7: return 'danger';
        default: return '';
      }
    },
    urgencyLevelText(level) {
      const levels = ['紧急', '一般', '低'];
      return levels[level - 1] || '未知';
    },
    priorityTagType(level) {
      switch (level) {
        case 1: return 'danger';
        case 2: return 'warning';
        case 3: return 'success';
        default: return '';
      }
    },
    sortByPriority(a, b) {
      // 紧急程度排序：1(紧急) > 2(一般) > 3(低)
      return a.priority - b.priority;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.handleSearch();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.handleSearch();
    },
    loadData() {
      // 加载数据，不传搜索条件时获取所有数据
      this.$axios.post('/api/queryAll/repair', {
        describe: '',
        communityId: this.filters.communityId,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        console.log('加载数据返回:', res.data);
        // 检查返回的数据结构
        if (res.data && res.data.content) {
          this.tableData = res.data.content;
          this.total = res.data.totalElements;
          console.log('loadData设置tableData:', this.tableData);
        } else if (res.data.code === 200 && res.data.data) {
          // 如果数据包装在data字段中
          this.tableData = res.data.data.content;
          this.total = res.data.data.totalElements;
          console.log('loadData设置tableData:', this.tableData);
        } else {
          this.$message.error('数据格式错误');
        }
      }).catch(error => {
        this.$message.error('网络错误，请稍后重试');
        console.error('加载数据错误:', error);
      });
    },
    submitAudit() {
      this.$refs.auditForm.validate((valid) => {
        if (valid) {
          // 准备提交的数据
          const submitData = {
            ...this.auditForm,
            handlerId: parseInt(this.auditForm.handlerId, 10), // 确保是数字类型
            id: this.auditForm.id // 确保id被包含在提交数据中
          };
          
          this.$axios.post('/api/audit/repair', submitData).then(res => {
            console.log('审核结果:', res.data);
            if (res.data.code === 200) {
              this.$message.success('审核成功');
              this.auditDialogVisible = false;
              this.handleSearch();
            } else {
              this.$message.error('审核失败');
            }
          }).catch(error => {
            this.$message.error('网络错误，请稍后重试');
            console.error('审核错误:', error);
          });
        } else {
          this.$message.error('表单验证失败');
        }
      });
    },
    loadCommunityList() {
      // 获取小区列表
      this.$axios.get('/api/repair/communityAll').then(res => {
        console.log('获取小区列表返回:', res.data);
        if (res.data && res.data.content) {
          this.communityList = res.data.content;
        } else if (res.data && Array.isArray(res.data)) {
          // 如果直接返回数组
          this.communityList = res.data;
        } else if (res.data.code === 200 && res.data.data) {
          // 如果包装在data字段中
          this.communityList = res.data.data.content || res.data.data;
        } else {
          this.$message.error('获取小区列表失败');
        }
        console.log('设置communityList:', this.communityList);
      }).catch(error => {
        this.$message.error('获取小区列表失败，请稍后重试');
        console.error('获取小区列表错误:', error);
        // 设置一些默认数据用于测试
        this.communityList = [
          { id: 1, name: '测试小区1' },
          { id: 2, name: '测试小区2' },
          { id: 3, name: '测试小区3' }
        ];
      });
    },
    handleCommunityChange(value) {
      this.filters.communityId = value;
      this.handleSearch();
    },
    loadPropertyStaffList() {
      // 实现加载物业人员列表的逻辑
      this.$axios.get('/api/repair/wcmPropertyUserAll').then(res => {
        console.log('获取物业人员列表返回:', res.data);
        if (res.data && res.data.content) {
          this.propertyStaffList = res.data.content;
        } else if (res.data && Array.isArray(res.data)) {
          // 如果直接返回数组
          this.propertyStaffList = res.data;
        } else if (res.data.code === 200 && res.data.data) {
          // 如果包装在data字段中
          this.propertyStaffList = res.data.data.content || res.data.data;
        } else {
          this.$message.error('获取物业人员列表失败');
        }
        console.log('设置propertyStaffList:', this.propertyStaffList);
      }).catch(error => {
        this.$message.error('获取物业人员列表失败，请稍后重试');
        console.error('获取物业人员列表错误:', error);
        // 设置一些默认数据用于测试
        this.propertyStaffList = [
          { id: 1, accountName: "admin", password: "123", phone: "18966364734" },
          { id: 2, accountName: "维修员1", password: "123", phone: "13812345678" },
          { id: 3, accountName: "维修员2", password: "123", phone: "13987654321" }
        ];
      });
    }
  }
};
</script>

<style scoped>
.property-repair-report {
  background: #fff;
  padding: 24px;
  border-radius: 6px;
}
.filter-form {
  margin-bottom: 20px;
}
.dialog-footer {
  text-align: right;
}
.el-form-item {
  margin-bottom: 18px;
}
.el-radio-group {
  display: flex;
  gap: 20px;
}
.el-select {
  width: 100%;
}
</style>
